package com.medi.chats.controller.page.m;

import com.medi.chats.config.WxMpConfig;
import com.medi.chats.consts.Consts;
import com.medi.chats.utils.MyConfig;
import com.medi.chats.utils.UserAgentUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/m")
public class WapPageController {
    @Autowired
    MyConfig myConfig;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @Description  微信端所有的url请求都加载同一个html
     * @Author        Administrator
     * @Date          2018/11/5 16:43
    */
    @RequestMapping(value = "/**", method = RequestMethod.GET)
    public String home(HttpServletRequest request) {
        // 判断是否是微信浏览器
        if (UserAgentUtil.isWechat(request)) {
            HttpSession session = request.getSession();
            if (session.getAttribute("chatUser") == null) {
                final WxMpService wxMpService = WxMpConfig.getMpService();

                // 微信获取用户信息
                String url = Consts.SERVER_URL + "/wx/cb/userInfoMp";   // 微信回调地址
                String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);

                // 当前请求的url
                StringBuffer targetUrl = request.getRequestURL();
                session.setAttribute("targetUrl", targetUrl);

                // 重定向到微信获取信息
                return "redirect:" + redirectUrl;
            } else {
                System.out.println("存在session");
            }
        }

        return "m/index";
    }
}
